import { Component, Input, Injector, ViewChild } from '@angular/core';
import { NzDrawerRef } from 'ng-zorro-antd';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import {
  UserEditDto,
  UserRoleDto,
  UserServiceProxy,
  CreateOrUpdateUserInput,
} from '@abp/service-proxies/service-proxies';
import { AppComponentBase } from '@abp/components';
import * as _ from 'lodash';

@Component({
  selector: 'create-or-edit-usersDrawer',
  templateUrl: './create-or-edit-user.component.html',
  styleUrls: ['./create-or-edit-user.component.less'],
})
export class CreateOrEditUserComponent extends AppComponentBase {
  @Input() id?: number;
  userForm: FormGroup;
  isLoadingBtn = false;

  user: UserEditDto = new UserEditDto();
  useDefaultPassword: boolean = true;
  roles: UserRoleDto[];

  loading = false;
  avatarUrl: string;

  constructor(
    injector: Injector,
    private drawerRef: NzDrawerRef,
    private fb: FormBuilder,
    private userService: UserServiceProxy,
  ) {
    super(injector);
  }

  ngOnInit() {
    this.userForm = this.fb.group({
      name: [null, [Validators.required, Validators.maxLength]],
      surname: [null, [Validators.required, Validators.maxLength]],
      emailAddress: [
        null,
        [Validators.email, Validators.required, Validators.maxLength],
      ],
      phoneNumber: [null, [Validators.maxLength]],
      userName: [null, [Validators.required, Validators.maxLength]],
      useDefaultPassword: [null],
      password: [null],
      shouldChangePasswordOnNextLogin: [null],
      isActive: [null],
      isLockoutEnabled: [null],
      isAssigned: [null],
    });
    this.userService.getUserForEdit(this.id).subscribe(userResult => {
      this.roles = userResult.roles;
      this.user = userResult.user;
      if (this.id) {
        this.useDefaultPassword = false;
      }
    });
  }

  getAssignedRoleCount(): number {
    return _.filter(this.roles, { isAssigned: true }).length;
  }

  close(): void {
    this.drawerRef.close(false);
  }

  submitForm(): void {
    for (const i in this.userForm.controls) {
      if (i == 'password' && this.useDefaultPassword) {
        this.userForm.controls[i].disable();
        this.userForm.controls[i].updateValueAndValidity();
        continue;
      }

      this.userForm.controls[i].markAsDirty();
      this.userForm.controls[i].updateValueAndValidity();
    }
    if (this.userForm.valid) {
      this.isLoadingBtn = true;
      const input = new CreateOrUpdateUserInput();
      input.user = this.user;
      input.setRandomPassword = this.useDefaultPassword;
      //界面没有显示此功能暂时都默认false：是否发送邮件
      input.sendActivationEmail = false;
      input.assignedRoleNames = _.map(
        _.filter(this.roles, { isAssigned: true }),
        role => role.roleName,
      );
      //暂时不支持选择组织结构
      input.organizationUnits = undefined;
      this.userService.createOrUpdateUser(input).subscribe(result => {
        this.isLoadingBtn = false;
        this.notify.success('操作成功！');
        this.drawerRef.close(true);
      });

      console.log(this.isLoadingBtn);
    }
  }
}
